import { apiUser } from "@/api/sys";
import { useUserStoreWithOut } from "@/stores/user";
import { tokenCache, userInfoCache } from "@/utils";
import type { Router } from "vue-router";

const whitelist = ["login", "poc", "redirect", "exception"];

/** 创建权限的路由守卫 */
export function createTokenGuard(router: Router) {
  const userStore = useUserStoreWithOut();

  router.beforeEach(async (to, _from, next) => {
    const matched = to.matched[0];

    // 白名单处理
    if (whitelist.indexOf(matched.name?.valueOf().toString() || "") < 0) {
      const token = tokenCache.get();
      if (!token) {
        console.warn("token is null");
        next({ name: "login", replace: true, query: { redirect: to.path } });
        return;
      } else {
        const user = userInfoCache.get();
        if (!user) {
          const current = await apiUser.getCurrent();
          if (current.value) {
            userStore.setUserInfo(current.value);
          }
        } else {
          userStore.setUserInfo(user);
        }
      }
    }
    next();
  });
}
